package yang.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yang.dao.BaseDaoI;
import yang.model.FinanceInfo;
import yang.model.HospitalUser;
import yang.model.PatientInfo;
import yang.pageModel.DataGrid;
import yang.pageModel.Json;
import yang.pageModel.Patient;
import yang.service.FinanceServiceI;
import yang.service.PatientServiceI;
import yang.util.DateTimeNow;

/**
 * 
 * @ClassName: PatientServiceImpl
 * @Description: 挂号单的服务
 * @author: Administrator
 * @date: 2014年6月29日 下午5:46:58
 */
@Service("patientService")
public class PatientServiceImpl implements PatientServiceI {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(PatientServiceImpl.class);

	private int nowNum = 1;// 是生成ID的后四位，按当天排序
	private BaseDaoI<PatientInfo> baseDao;// patientImpl
	private BaseDaoI<HospitalUser> userDao;
	private BaseDaoI<FinanceInfo> financeDao;

	private FinanceServiceI financeService;

	/**
	 * 
	 * @Title: findPatient
	 * @Description: 查找挂号单的实现
	 * @param info
	 * @return
	 * @see yang.service.PatientServiceI#findPatient(yang.pageModel.Patient)
	 */
	@Override
	public DataGrid findPatient(Patient info) {

		String hql = "from PatientInfo p where 1=1";// 查询语句
		logger.info("建立了查询语句");
		DataGrid dataGrid = new DataGrid();// 创建DATA
		Map<String, Object> params = new HashMap<String, Object>();// 查询条件
		hql = addWhere(info, hql, params);// 为语句增加WHERE条件
		String totalHql = "select count(*) " + hql;// 查询总数的语句
		hql = addOrder(info, hql);// 为查询语句增加ORDER条件
		List<PatientInfo> list = baseDao.find(hql, params, info.getPage(),
				info.getRows());// 进行查询
		List<Patient> list2 = new ArrayList<Patient>();// 建立模型
		changeModel(list, list2);// 为模型赋值
		dataGrid.setRows(list2);// 向前台输出了
		dataGrid.setTotal(baseDao.count(totalHql, params));
		logger.info("返回ACTION");
		return dataGrid;
	}

	/**
	 * @Title: changeModel
	 * @Description: 为模型赋值
	 * @param list
	 * @param list2
	 * @return: void
	 */
	private void changeModel(List<PatientInfo> list, List<Patient> list2) {
		if (list != null && list.size() > 0) {
			for (PatientInfo patientInfo : list) {
				Patient patient = new Patient();
				BeanUtils.copyProperties(patientInfo, patient);
				patient.setDoctorName(patientInfo.getHospitalUser()
						.getUserTruename());
				patient.setPatientPrice(patientInfo.getHospitalUser()
						.getUserPrice());
				if (patientInfo.getPatientSex() == 0
						|| patientInfo.getPatientSex() == null) {
					patient.setSex("女");
				} else {
					patient.setSex("男");
				}
				StringBuffer s = new StringBuffer("YY");
				for (int i = 0; i < 4 - patientInfo.getPatientTodayid()
						.toString().length(); i++) {
					s.append("0");
				}
				s.append(patientInfo.getPatientTodayid().toString());
				patient.setTodayid(s.toString());
				list2.add(patient);
				logger.info("完成赋值");
			}
		}
	}

	/**
	 * 
	 * @方法:增加ORDER条件
	 * @author:阳 2014年6月8日
	 */
	private String addOrder(Patient info, String hql) {
		if (info.getSort() != null) {
			if (info.getSort().equals("sex")) {
				info.setSort("patientSex");
			}
			hql += " order by " + info.getSort() + " " + info.getOrder();
		}
		logger.info("添加了方法");
		return hql;
	}

	/**
	 * 
	 * @Title: addWhere
	 * @Description: 添加查询条件
	 * @param info
	 * @param hql
	 * @param params
	 * @return
	 * @return: String
	 */
	private String addWhere(Patient info, String hql, Map<String, Object> params) {
		if (info.getInputText() != null
				&& !info.getInputText().trim().equals("")) {
			hql += " and p.patientName like :patientName";
			params.put("patientName", "%%" + info.getInputText() + "%%");
		}
		if (info.getPatientType() != null) {
			hql += " and p.patientType<=:patientType";
			params.put("patientType", info.getPatientType());
		}
		if (info.getDoctorId() != 0) {
			hql += " and p.hospitalUser.userNo=:doctorId";
			params.put("doctorId", info.getDoctorId());
		}
		logger.info("添加了查询条件");
		return hql;
	}

	/**
	 * @Title: savePatients
	 * @Description: 新建一个挂号
	 * @param info
	 * @return 返回一个挂号单
	 * @see yang.service.PatientServiceI#savePatients(yang.pageModel.Patient)
	 */
	@Override
	public Patient savePatients(Patient info) {
		PatientInfo patientInfo = new PatientInfo();
		checkNo();// 进行判断是否是新的一天
		BeanUtils.copyProperties(info, patientInfo);
		nowNum++;
		patientInfo.setPatientId(UUID.randomUUID().toString());
		patientInfo.setPatientTodayid(nowNum);
		patientInfo.setHospitalUser(userDao.get(HospitalUser.class,
				info.getDoctorId()));
		patientInfo.setPatientDate(new Timestamp(System.currentTimeMillis()));
		patientInfo.setPatientType(0);
		baseDao.save(patientInfo);
		BeanUtils.copyProperties(patientInfo, info);
		info.setDoctorName(patientInfo.getHospitalUser().getUserNicheng());
		logger.info("生成了一个挂号单");
		return info;
	}

	/**
	 * @Title: checkNo
	 * @Description: 提取出来的方法，判断日期
	 * @return: void
	 */
	private void checkNo() {
		PatientInfo patientInfo;
		patientInfo = baseDao
				.get("from PatientInfo p order by p.patientDate desc");
		String nowTime;
		if (patientInfo!=null) {
			nowTime= patientInfo.getPatientDate().toString()
					.substring(0, 10);
		}else {
			nowTime="";
		}
		
		String timeNum = DateTimeNow.getDate();
		logger.info(nowTime);
		if (!nowTime.equals(String.valueOf(timeNum)) || nowTime.equals("")
				|| nowTime == null) {
			nowNum = 0;
		} else {
			nowNum = patientInfo.getPatientTodayid();
			logger.info(nowNum);
		}
		logger.info("验证完成");
	}

	/**
	 * 
	 * @Title: updatePatient
	 * @Description: 修改挂号单
	 * @param info
	 * @see yang.service.PatientServiceI#updatePatient(yang.pageModel.Patient)
	 */
	@Override
	public void updatePatient(Patient info) {
		PatientInfo patientInfo = baseDao.get(PatientInfo.class,
				info.getPatientId());
		patientInfo.setPatientType(patientInfo.getPatientType() + 1);
		baseDao.update(patientInfo);
		logger.info("修改了挂号单");
	}

	/**
	 * 
	 * @Title: deletePatient
	 * @Description: 删除挂号单的服务
	 * @param info
	 * @see yang.service.PatientServiceI#deletePatient(yang.pageModel.Patient)
	 */
	@Override
	public Json deletePatient(Patient info) {
		Json json = new Json();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("patientId", info.getPatientId());
		PatientInfo o = baseDao.get(
				"from PatientInfo p where p.patientId=:patientId", params);
		try {
			baseDao.delete(o);
			json.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("删除了一个挂号单");
		return json;

	}

	/**
	 * 
	 * @Title: updatePatientWhen12
	 * @Description: 实现更新
	 * @see yang.service.PatientServiceI#updatePatientWhen12()
	 */
	@Override
	public void updatePatientWhen12() {
		financeService.uodateBy12();
		int type = 10;
		List<PatientInfo> infos = baseDao
				.find("from PatientInfo p where p.patientType<10");
		for (PatientInfo patientInfo : infos) {
			patientInfo.setPatientType(type);
			baseDao.saveOrUpdate(patientInfo);
			FinanceInfo info = new FinanceInfo();
			info.setFinanceMoney(patientInfo.getHospitalUser().getUserPrice());
			info.setFinanceTime(new Timestamp(System.currentTimeMillis()));
			info.setFinanceType("挂号费");
			info.setId(UUID.randomUUID().toString());
			financeDao.save(info);
		}
	}

	// ----- get set --------
	public BaseDaoI<HospitalUser> getUserDao() {
		return userDao;
	}

	@Autowired
	public void setUserDao(BaseDaoI<HospitalUser> userDao) {
		this.userDao = userDao;
	}

	public BaseDaoI<PatientInfo> getBaseDao() {
		return baseDao;
	}

	@Autowired
	public void setBaseDao(BaseDaoI<PatientInfo> baseDao) {
		logger.info("注入了dao");
		this.baseDao = baseDao;
	}

	public BaseDaoI<FinanceInfo> getFinanceDao() {
		return financeDao;
	}

	@Autowired
	public void setFinanceDao(BaseDaoI<FinanceInfo> financeDao) {
		this.financeDao = financeDao;
	}

	public FinanceServiceI getFinanceService() {
		return financeService;
	}

	@Autowired
	public void setFinanceService(FinanceServiceI financeService) {
		this.financeService = financeService;
	}

}
